package com.gfxy.aspect;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.util.oConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: lijixin 2021/5/25 5:07 下午
 */
@Aspect
@Component
public class PlantformDictAspect {
    private static final Logger log = LoggerFactory.getLogger(PlantformDictAspect.class);
    @Autowired
    private CommonAPI commonAPI;

    public PlantformDictAspect() {
    }

    @Pointcut("execution(public * com.gfxy..*.*Controller.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time1 = System.currentTimeMillis();
        Object result = pjp.proceed();
        long time2 = System.currentTimeMillis();
        log.debug("获取JSON数据 耗时：" + (time2 - time1) + "ms");
        long start = System.currentTimeMillis();
        this.parseDictText(result);
        long end = System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时" + (end - start) + "ms");
        return result;
    }

    private void parseDictText(Object result) {
        if (result instanceof Result && ((Result)result).getResult() instanceof IPage) {
            List<JSONObject> items = new ArrayList();
            Iterator var3 = ((IPage)((Result)result).getResult()).getRecords().iterator();

            while(var3.hasNext()) {
                Object record = var3.next();
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";

                try {
                    json = mapper.writeValueAsString(record);
                } catch (JsonProcessingException var17) {
                    log.error("json解析失败" + var17.getMessage(), var17);
                }

                JSONObject item = JSONObject.parseObject(json);
                Field[] var8 = oConvertUtils.getAllFields(record);
                int var9 = var8.length;

                for(int var10 = 0; var10 < var9; ++var10) {
                    Field field = var8[var10];
                    if (field.getAnnotation(Dict.class) != null) {
                        String code = ((Dict)field.getAnnotation(Dict.class)).dicCode();
                        String text = ((Dict)field.getAnnotation(Dict.class)).dicText();
                        String table = ((Dict)field.getAnnotation(Dict.class)).dictTable();
                        String key = String.valueOf(item.get(field.getName()));
                        String textValue = this.translateDictValue(code, text, table, key);
                        log.debug(" 字典Val : " + textValue);
                        log.debug(" __翻译字典字段__ " + field.getName() + "_dictText" + "： " + textValue);
                        item.put(field.getName() + "_dictText", textValue);
                    }

                    if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                        SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        item.put(field.getName(), aDate.format(new Date((Long)item.get(field.getName()))));
                    }
                }

                items.add(item);
            }

            ((IPage)((Result)result).getResult()).setRecords(items);
        } else if(result instanceof Result && ((Result)result).getResult() instanceof Collection){

            Iterator var3 = ((Collection)((Result<?>) result).getResult()).iterator();
            List<JSONObject> items = translateDict(var3);
            ((Result<List>) result).setResult(items);
        }

    }

    private List<JSONObject> translateDict(Iterator var3){
        List<JSONObject> items = new ArrayList<>();
        while(var3.hasNext()) {
            Object record = var3.next();
            ObjectMapper mapper = new ObjectMapper();
            String json = "{}";

            try {
                json = mapper.writeValueAsString(record);
            } catch (JsonProcessingException var17) {
                log.error("json解析失败" + var17.getMessage(), var17);
            }

            JSONObject item = JSONObject.parseObject(json);
            Field[] var8 = oConvertUtils.getAllFields(record);
            int var9 = var8.length;

            for(int var10 = 0; var10 < var9; ++var10) {
                Field field = var8[var10];
                if (field.getAnnotation(Dict.class) != null) {
                    String code = ((Dict)field.getAnnotation(Dict.class)).dicCode();
                    String text = ((Dict)field.getAnnotation(Dict.class)).dicText();
                    String table = ((Dict)field.getAnnotation(Dict.class)).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    String textValue = this.translateDictValue(code, text, table, key);
                    log.debug(" 字典Val : " + textValue);
                    log.debug(" __翻译字典字段__ " + field.getName() + "_dictText" + "： " + textValue);
                    item.put(field.getName() + "_dictText", textValue);
                }

                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long)item.get(field.getName()))));
                }
            }

            items.add(item);
        }
        return items;
    }

    private String translateDictValue(String code, String text, String table, String key) {
        if (oConvertUtils.isEmpty(key)) {
            return null;
        } else {
            StringBuffer textValue = new StringBuffer();
            String[] keys = key.split(",");
            String[] var7 = keys;
            int var8 = keys.length;

            for(int var9 = 0; var9 < var8; ++var9) {
                String k = var7[var9];
                String tmpValue = null;
                log.debug(" 字典 key : " + k);
                if (k.trim().length() != 0) {
                    if (!StringUtils.isEmpty(table)) {
                        log.debug("--DictAspect------dicTable=" + table + " ,dicText= " + text + " ,dicCode=" + code);
                        tmpValue = this.commonAPI.translateDictFromTable(table, text, code, k.trim());
                    } else {
                        tmpValue = this.commonAPI.translateDict(code, k.trim());
                    }

                    if (tmpValue != null) {
                        if (!"".equals(textValue.toString())) {
                            textValue.append(",");
                        }

                        textValue.append(tmpValue);
                    }
                }
            }

            return textValue.toString();
        }
    }
}
